'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconEye, IconEyeOff, IconLock, IconBuilding, IconPhone, IconUser, IconShield } from "@tabler/icons-react"
import Link from 'next/link'
import { LIVENESS_BASE_URL } from '@/lib/config'

export default function RegisterPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    phone: '',
    username: '',
    password: '',
    confirmPassword: '',
    role: 'user' // 默认普通用户
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    // 清除错误信息
    if (error) setError('')
    if (success) setSuccess('')
  }

  const validateForm = () => {
    if (!formData.phone || !formData.username || !formData.password || !formData.confirmPassword || !formData.role) {
      setError('请填写所有必填项')
      return false
    }

    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      setError('请输入有效的手机号码')
      return false
    }

    if (formData.username.length < 3 || formData.username.length > 20) {
      setError('用户名长度应在3-20个字符之间')
      return false
    }

    if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(formData.username)) {
      setError('用户名只能包含字母、数字、下划线和中文')
      return false
    }

    if (formData.password.length < 6) {
      setError('密码至少需要6个字符')
      return false
    }

    if (formData.password !== formData.confirmPassword) {
      setError('两次输入的密码不一致')
      return false
    }

    return true
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }

    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      // 调用真实的注册API
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/auth/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          phone: formData.phone,
          username: formData.username,
          password: formData.password,
          role: formData.role
        })
      })

      const result = await response.json()

      if (!response.ok) {
        throw new Error(result.message || '注册失败')
      }

      if (result.success) {
        setSuccess(`注册成功！您的用户名是：${result.username}，正在跳转到登录页面...`)
        
        // 3秒后跳转到登录页，让用户看清用户名
        setTimeout(() => {
          router.push('/login')
        }, 3000)
      } else {
        setError(result.message || '注册失败，请重试')
      }
      
    } catch (err: any) {
      console.error('注册错误:', err)
      if (err.message.includes('用户名已存在')) {
        setError('用户名已被使用，请更换其他用户名')
      } else if (err.message.includes('手机号已存在')) {
        setError('该手机号已注册，请直接登录或使用其他手机号')
      } else {
        setError(err.message || '注册失败，请检查网络连接或稍后重试')
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen gradient-bg flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo 和标题 */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center shadow-lg">
              <IconBuilding className="w-8 h-8 text-blue-600" />
            </div>
            <div className="text-left">
              <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                医疗空间数字孪生
              </h1>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Medical Space Digital Twin
              </p>
            </div>
          </div>
        </div>

        {/* 注册表单 */}
        <Card className="glass-effect border border-white/20 dark:border-gray-700/20 shadow-xl">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              账号注册
            </CardTitle>
            <CardDescription className="text-gray-600 dark:text-gray-400">
              请填写您的注册信息
            </CardDescription>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <form onSubmit={handleSubmit} className="space-y-4">
                            

              {/* 手机号 */}
              <div className="space-y-2">
                <Label htmlFor="phone" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  手机号 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <IconPhone className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="请输入手机号码"
                    autoComplete="tel"
                    className="pl-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                </div>
              </div>

              {/* 用户名 */}
              <div className="space-y-2">
                <Label htmlFor="username" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  用户名 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <IconUser className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="username"
                    name="username"
                    type="text"
                    value={formData.username}
                    onChange={handleInputChange}
                    placeholder="请输入用户名（3-20个字符）"
                    className="pl-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  用户名将用于登录，支持字母、数字、下划线和中文
                </p>
              </div>

              {/* 用户角色 */}
              <div className="space-y-2">
                <Label htmlFor="role" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  用户角色 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <IconShield className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <select
                    id="role"
                    name="role"
                    value={formData.role}
                    onChange={(e) => setFormData(prev => ({...prev, role: e.target.value}))}
                    className="w-full pl-10 pr-3 py-2 bg-white/80 dark:bg-gray-800/80 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                    disabled={isLoading}
                  >
                    <option value="user">普通用户 - 基础功能访问权限</option>
                    <option value="admin">管理员 - 完整系统管理权限</option>
                  </select>
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  管理员账号需要人脸验证登录
                </p>
              </div>

              {/* 密码 */}
              <div className="space-y-2">
                <Label htmlFor="password" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  密码 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="password"
                    name="password"
                    type={showPassword ? 'text' : 'password'}
                    value={formData.password}
                    onChange={handleInputChange}
                    placeholder="请输入密码（至少6个字符）"
                    autoComplete="new-password"
                    className="pl-10 pr-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    disabled={isLoading}
                  >
                    {showPassword ? (
                      <IconEyeOff className="w-4 h-4" />
                    ) : (
                      <IconEye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* 确认密码 */}
              <div className="space-y-2">
                <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  确认密码 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="confirmPassword"
                    name="confirmPassword"
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={formData.confirmPassword}
                    onChange={handleInputChange}
                    placeholder="请再次输入密码"
                    autoComplete="new-password"
                    className="pl-10 pr-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    disabled={isLoading}
                  >
                    {showConfirmPassword ? (
                      <IconEyeOff className="w-4 h-4" />
                    ) : (
                      <IconEye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* 错误提示 */}
              {error && (
                <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
                  <AlertDescription className="text-red-700 dark:text-red-300">
                    {error}
                  </AlertDescription>
                </Alert>
              )}

              {/* 成功提示 */}
              {success && (
                <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
                  <AlertDescription className="text-green-700 dark:text-green-300">
                    {success}
                  </AlertDescription>
                </Alert>
              )}

              {/* 注册按钮 */}
              <Button
                type="submit"
                className="w-full h-12 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-medium rounded-lg shadow-lg hover:shadow-xl transition-all duration-200"
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="flex items-center gap-2">
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    注册中...
                  </div>
                ) : (
                  '注册'
                )}
              </Button>
            </form>

            {/* 登录链接 */}
            <div className="text-center pt-4 border-t border-gray-200 dark:border-gray-700">
              <p className="text-sm text-gray-600 dark:text-gray-400">
                已有账号？
                <Link
                  href="/login"
                  className="ml-1 text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 font-medium transition-colors"
                >
                  立即登录
                </Link>
              </p>
            </div>
          </CardContent>
        </Card>

      </div>
    </div>
  )
}
